"""
参数管理模块路由
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from ..db import get_db
from ..schemas import Parameter, ParameterCreate, ParameterUpdate, MessageResponse
from ..db.parameters.crud import (
    create_parameter, get_parameter_by_name_en, get_parameters_simple,
    update_parameter, delete_parameter, get_project_by_name_en,
    get_parameter_category_by_name_en
)

router = APIRouter(prefix="/api/projects/{project_name_en}/categories/{category_name_en}/parameters", tags=["参数管理"])


@router.post("", response_model=Parameter, status_code=201)
async def create_parameter_endpoint(
    project_name_en: str,
    category_name_en: str,
    parameter: ParameterCreate,
    db: Session = Depends(get_db)
):
    """创建参数"""
    # 检查项目是否存在
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    # 检查分类是否存在
    category = get_parameter_category_by_name_en(db, project.id, category_name_en)
    if not category:
        raise HTTPException(
            status_code=404,
            detail=f"分类 '{category_name_en}' 不存在"
        )
    
    # 检查参数英文名称是否已存在
    existing_parameter = get_parameter_by_name_en(db, category.id, parameter.name_en)
    if existing_parameter:
        raise HTTPException(
            status_code=400,
            detail=f"参数英文名称 '{parameter.name_en}' 已存在"
        )
    
    return create_parameter(db, parameter, category.id, project.time_horizon)


@router.get("")
async def get_parameters_endpoint(
    project_name_en: str,
    category_name_en: str,
    db: Session = Depends(get_db)
):
    """获取参数列表"""
    # 检查项目是否存在
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    # 检查分类是否存在
    category = get_parameter_category_by_name_en(db, project.id, category_name_en)
    if not category:
        raise HTTPException(
            status_code=404,
            detail=f"分类 '{category_name_en}' 不存在"
        )
    
    parameters = get_parameters_simple(db, category.id)
    # 手动转换为字典
    result = []
    for param in parameters:
        result.append({
            "id": param.id,
            "name": param.name,
            "name_en": param.name_en,
            "param_type": param.param_type,
            "unit": param.unit,
            "description": param.description,
            "is_list": param.is_list,
            "is_year_related": getattr(param, "is_year_related", False),
            "list_length": param.list_length,
            "sort_order": param.sort_order,
            "category_id": param.category_id,
            "created_at": param.created_at.isoformat() if param.created_at else None,
            "updated_at": param.updated_at.isoformat() if param.updated_at else None
        })
    return result


@router.put("/{param_name_en}", response_model=Parameter)
async def update_parameter_endpoint(
    project_name_en: str,
    category_name_en: str,
    param_name_en: str,
    parameter_update: ParameterUpdate,
    db: Session = Depends(get_db)
):
    """更新参数"""
    # 检查项目是否存在
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    # 检查分类是否存在
    category = get_parameter_category_by_name_en(db, project.id, category_name_en)
    if not category:
        raise HTTPException(
            status_code=404,
            detail=f"分类 '{category_name_en}' 不存在"
        )
    
    # 检查参数是否存在
    parameter = get_parameter_by_name_en(db, category.id, param_name_en)
    if not parameter:
        raise HTTPException(
            status_code=404,
            detail=f"参数 '{param_name_en}' 不存在"
        )
    
    updated_parameter = update_parameter(db, parameter.id, parameter_update)
    return updated_parameter


@router.delete("/{param_name_en}", response_model=MessageResponse)
async def delete_parameter_endpoint(
    project_name_en: str,
    category_name_en: str,
    param_name_en: str,
    db: Session = Depends(get_db)
):
    """删除参数"""
    # 检查项目是否存在
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    # 检查分类是否存在
    category = get_parameter_category_by_name_en(db, project.id, category_name_en)
    if not category:
        raise HTTPException(
            status_code=404,
            detail=f"分类 '{category_name_en}' 不存在"
        )
    
    # 检查参数是否存在
    parameter = get_parameter_by_name_en(db, category.id, param_name_en)
    if not parameter:
        raise HTTPException(
            status_code=404,
            detail=f"参数 '{param_name_en}' 不存在"
        )
    
    success = delete_parameter(db, parameter.id)
    if success:
        return MessageResponse(message=f"参数 '{param_name_en}' 删除成功")
    else:
        raise HTTPException(
            status_code=500,
            detail="删除参数失败"
        )

